package com.wing.bill.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.bill.dao.BillOrdPayInformationDao;
import com.wing.bill.model.entity.*;
import com.wing.bill.model.request.BillOrdPayInformationForm;
import com.wing.bill.model.response.BillOrdPayInformationVO;
import com.wing.cabinet.model.response.EnterpricceIdVO;
import com.wing.cabinet.service.EnterpricceIdService;
import com.wing.common.utils.JsonResult;
import com.wing.util.PulsarCommons;
import com.wing.util.PulsarUtils;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.pulsar.client.api.PulsarClientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 账单付款信息-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class BillOrdPayInformationServiceImpl extends ServiceImpl<BillOrdPayInformationDao, BillOrdPayInformation> implements BillOrdPayInformationService {

    @Value("${pulsar.client.topicUrl}")
    private String topicUrl;

    @Autowired
    private BillOrdInformationService billOrdInformationService;
    @Autowired
    private BillOrdInformationDetailService billOrdInformationDetailService;
    @Autowired
    BillOrdRepairInformationDetailService billOrdRepairInformationDetailService;
    @Autowired
    private EnterpricceIdService enterpricceIdService;
    @Override
    public int add(BillOrdPayInformationForm billOrdPayInformationForm) {

        //校验

        BillOrdPayInformation billOrdPayInformation =new BillOrdPayInformation();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(BillOrdPayInformation.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(billOrdPayInformationForm, billOrdPayInformation, copyOptions);

        return baseMapper.insert(billOrdPayInformation);
    }

    @Override
    public List<BillOrdPayInformationVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<BillOrdPayInformationVO> pageList4app(Page page, Map<String, Object> params) {
        List<BillOrdPayInformationVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public BillOrdPayInformationVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    public JsonResult addAll(BillOrdPayInformationForm billOrdPayInformationForm) {
        //企业在修磨和领新时传付款凭证
        if (baseMapper.find(billOrdPayInformationForm.getBillNo())==0){//添加第一张付款凭证时，改这两张表的状态
            BillOrdInformation boi = new BillOrdInformation();
            boi.setBillNo(billOrdPayInformationForm.getBillNo())
                    .setBillStatus(BillOrdInformation.BillStatus.settled)
                    .setId((Long) billOrdInformationService.find(billOrdPayInformationForm.getBillNo()).get("id"));
            billOrdInformationService.updateById(boi);
            //todo 同步
            try{
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("type", "Update");
                jsonObject.put("data", boi);
                PulsarUtils.send(topicUrl+ PulsarCommons.BILL_ORD_INFORMATION_TOPIC,jsonObject.toJSONString());
            }catch (Exception e) {
                log.error(PulsarCommons.BILL_ORD_INFORMATION_TOPIC+"同步失败",e);
            }
            if (billOrdPayInformationForm.getType().equals(BillOrdPayInformation.Type.collect)){//领新账单改领新细节表
                BillOrdInformationDetail boid = new BillOrdInformationDetail();
                boid.setStatus(BillOrdInformationDetail.Status.settled)
                        .setBillNo(billOrdPayInformationForm.getBillNo());
                QueryWrapper<BillOrdInformationDetail> queryWrapperDetail = new QueryWrapper<>();
                queryWrapperDetail.eq("bill_no",billOrdPayInformationForm.getBillNo());
                billOrdInformationDetailService.update(boid,queryWrapperDetail);
                try{
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("type", "Update");
                    jsonObject.put("data", boid);
                    PulsarUtils.send(topicUrl+ PulsarCommons.BILL_ORD_INFORMATION_DETAIL_TOPIC,jsonObject.toJSONString());
                }catch (Exception e) {
                    log.error(PulsarCommons.BILL_ORD_INFORMATION_DETAIL_TOPIC+"同步失败",e);
                }
            }
            if(billOrdPayInformationForm.getType().equals(BillOrdPayInformation.Type.repair)){//修磨账单改修磨细节表
                BillOrdRepairInformationDetail borif = new BillOrdRepairInformationDetail();
                borif.setStatus(BillOrdRepairInformationDetail.Status.settled)
                        .setBillNo(billOrdPayInformationForm.getBillNo());
                QueryWrapper<BillOrdRepairInformationDetail> queryWrapperDetail = new QueryWrapper<>();
                queryWrapperDetail.eq("bill_no",billOrdPayInformationForm.getBillNo());
                billOrdRepairInformationDetailService.update(borif,queryWrapperDetail);
                try{
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("type", "Update");
                    jsonObject.put("data", borif);
                    PulsarUtils.send(topicUrl+ PulsarCommons.BILL_ORD_REPAIR_INFORMATION_DETAIL_TOPIC,jsonObject.toJSONString());
                }catch (Exception e) {
                    log.error(PulsarCommons.BILL_ORD_REPAIR_INFORMATION_DETAIL_TOPIC+"同步失败",e);
                }
            }

            //todo 同步
        }
        if (billOrdPayInformationForm.getTransferor().equals(BillOrdPayInformation.Transferor.self)||billOrdPayInformationForm.getPayName()==null||billOrdPayInformationForm.equals("")){//本人转账 付款人为登录用户
            billOrdPayInformationForm.setPayName(JwtUtils.getLoginUsername());
        }
        BillOrdPayInformation bopi = new BillOrdPayInformation();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(BillOrdPayInformation.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(billOrdPayInformationForm, bopi, copyOptions);
        if (baseMapper.insert(bopi) > 0) {
            //todo 同步
            try {
                EnterpricceIdVO enterpricceIdVO = enterpricceIdService.getEnterpricceIdVO();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("type", "add");
                jsonObject.put("data", bopi);
                jsonObject.put("enterpriseId",enterpricceIdVO.getEnterpriseId());
                PulsarUtils.send(topicUrl+ PulsarCommons.BILL_ORD_PAY_INFORMATION_TOPIC,jsonObject.toJSONString());
            } catch (PulsarClientException e) {
                log.error(PulsarCommons.BILL_ORD_PAY_INFORMATION_TOPIC+"同步失败",e);
            }
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }
}
